package com.cskaoyan.config;

import com.cskaoyan.converter.String2DateConverter;
import com.cskaoyan.interceptor.HandlerInterceptor1;
import com.cskaoyan.interceptor.HandlerInterceptor2;
import com.cskaoyan.interceptor.HandlerInterceptor3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Primary;
import org.springframework.core.convert.support.ConfigurableConversionService;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;

/**
 * 实现WebMvcConfigurer，需要实现里面的方法做对应配置 → mvc开头的标签的配置
 * @author stone
 * @date 2022/05/03 17:35
 */
@ComponentScan("com.cskaoyan.controller")
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {

    @Bean
    public CommonsMultipartResolver multipartResolver() {
        return new CommonsMultipartResolver();
    }

    /*@Autowired
    ConfigurableConversionService conversionService;

    //自定义init方法
    @PostConstruct
    public void addConverter() {
        conversionService.addConverter(new String2DateConverter());
    }

    @Primary //首要、首先
    @Bean
    public ConfigurableConversionService conversionService() {
        return conversionService;
    }*/

    // 自定义converter配置
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new String2DateConverter());
    }

    // 静态资源映射的配置
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //                                      mapping属性                      location属性
        registry.addResourceHandler("/pic/**").addResourceLocations("file:d:/tmp/");
        //registry.addResourceHandler("/pic/**").addResourceLocations("file:d:/tmp/");
    }

    // HandlerInterceptor的配置
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor1());//默认作用范围是全局，书写顺序就是顺序
        registry.addInterceptor(new HandlerInterceptor2());
        registry.addInterceptor(new HandlerInterceptor3()).addPathPatterns("/user/**");//addPathPatterns指定作用范围
    }
}
